﻿/* Ree7 Tile Toolkit for Windows Phone
 * Copyright (C) 2011-2014 Pierre BELIN <pierre@ree7.fr>, and project contributors.
 *
 * Distributed under the Microsoft Public License (Ms-PL).
 * See accompanying file License.txt */

using System;
using System.IO;
using System.IO.IsolatedStorage;
using System.Windows;
using System.Windows.Controls;
using Microsoft.Phone.Shell;
using Ree7.Utils.Imaging;

namespace Ree7.TileToolkit
{
	/// <summary>
	/// XAML container that mimicks the look (size, accent color) of a ShellTile.
	/// Provides method to export its visual (content) as an image file in the IsolatedStorage for use in a real ShellTile
	/// </summary>
	[TemplatePart(Name = "SolidBackground", Type = typeof(UIElement))]
	public class CustomTile : ContentControl
	{
		UIElement SolidBackground;

		internal CustomTile()
		{
			DefaultStyleKey = typeof(CustomTile);
		}

		public override void OnApplyTemplate()
		{
			base.OnApplyTemplate();
			SolidBackground = GetTemplateChild("SolidBackground") as UIElement;
		}

		public string IsolatedStorageFileName
		{
			get
			{
				if (String.IsNullOrEmpty(this.Name))
					throw new InvalidOperationException("Name is undefined, cannot generate a file name for this tile. Please specify an unique name for the tile first.");

				return String.Format("Shared/ShellContent/{0}.png", this.Name);
			}
		}

		/// <summary>
		/// Renders a PNG representation of the control in outputStream
		/// </summary>
        public void RenderAsPNG(Stream outputStream)
        {
            // Force the content to layout itself properly as it might never have been added in the visual tree (rendered) before.
            Size containerSz = new Size(this.Width, this.Height);
            Point containerOrigin = new Point(0, 0);

            UIElement content = (UIElement)this.Content;
            content.Measure(containerSz);
            content.Arrange(new Rect(containerOrigin, containerSz));

            ControlToPng.RenderAsPNGStream(content, outputStream);
        }

		/// <summary>
		/// Save the tile in the application's IsolatedStorage
		/// </summary>
		/// <returns>The URI of the saved file</returns>
		public Uri SavePNGToIsolatedStorage()
		{
			// Obtain the virtual store for the application.
			IsolatedStorageFile myStore = IsolatedStorageFile.GetUserStoreForApplication();
			using (IsolatedStorageFileStream fileStream = new IsolatedStorageFileStream(IsolatedStorageFileName, FileMode.Create, myStore))
			{
				/*MemoryStream ms = (MemoryStream)RenderAsPNG();
				byte[] b = ms.GetBuffer();
                
				fileStream.Write(b, 0, b.Length);
				fileStream.Flush();
				fileStream.Close();*/

                RenderAsPNG(fileStream);
			}

			return new Uri("isostore:/" + IsolatedStorageFileName, UriKind.Absolute);
		}

		/// <summary>
		/// Returns the ShellTileData for displaying this CustomTile in a call to ShellTile.Create().
		/// You can customize the returned ShellTileData to enable more features like Mango's back side
		/// of tile but do not edit its Title and BackgroundImage properties.
		/// </summary>
		[Obsolete("See CustomTileHelper for updated features")]
		public StandardTileData GetShellTileData()
		{
			Uri isoStoreRenderedImage = SavePNGToIsolatedStorage();
			return new StandardTileData()
			{
				Title = " ",    // tile title is already embedded in the image
				BackgroundImage = isoStoreRenderedImage
			};
		}
	}
}
